<template>
  <div class="app-container">
    <!-- 页面顶部保存按钮 - 靠右显示，文字改为确认绑定 -->
    <div class="top-actions" style="margin-bottom: 5px; text-align: right;">
      <el-button
        type="primary"
        @click="handleSave"
        :disabled="!selectedPost || !selectedDevice"
      >
        确认绑定
      </el-button>
    </div>

    <!-- 三列布局，设置高度为200px -->
    <el-row :gutter="10" class="mb8" style="height: calc(100vh - 220px)">
      <!-- 左侧：设备类型列表 - 高度设置为100% -->
      <el-col :span="4" style="height: 100%;">
        <div class="list-container">
          <div class="list-header">设备类型</div>
          <div class="list-content">
            <div
              v-for="item in deviceTypeOptions"
              :key="item.value"
              class="list-item"
              :class="{ 'list-item-selected': selectedDeviceType === item.value }"
              @click="handleDeviceTypeClick(item)"
            >
              工位 <---> {{ item.label }}
            </div>
            <div v-if="deviceTypeOptions.length === 0" class="empty-tip">暂无设备类型数据</div>
          </div>
        </div>
      </el-col>

      <!-- 中间列：产线树与工位列表 - 高度设置为100% -->
      <el-col :span="10" style="height: 100%;">
        <div class="list-container">
          <div class="list-header">
            <div class="header-title">产线与工位</div>
            <!-- 工位搜索条件 -->
            <el-form :inline="true" :model="postSearchForm" class="search-form">
              <el-form-item label="产线">
                <treeselect v-model="postSearchForm.deptId" :options="deptList" :flat="true" :normalizer="normalizer"
                            placeholder="产线" style="width: 200px;"/>
              </el-form-item>
              <el-form-item label="工位名称">
                <el-input v-model="postSearchForm.name" placeholder="工位名称" size="small" style="width: 120px;"/>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="handlePostSearch" size="small">搜索</el-button>
                <el-button @click="resetPostSearch" size="small">重置</el-button>
              </el-form-item>
            </el-form>
          </div>
          <div class="list-content">
            <div
              v-for="item in simpleList"
              :key="item.id"
              class="list-item"
              :class="{ 'list-item-selected': selectedPost && selectedPost.id === item.id }"
              @click="handlePostClick(item)"
            >
              {{ item.name }}
              <span v-if="item.deviceList && item.deviceList.length>0" style="padding-left: 5px">
                (<span v-for="device in item.deviceList">
                {{device.deviceName}}
              </span>)
              </span>
            </div>
            <div v-if="simpleList.length === 0" class="empty-tip">暂无工位数据</div>
          </div>
        </div>
      </el-col>

      <!-- 右边列：设备列表 - 高度设置为100% -->
      <el-col :span="10" style="height: 100%;">
        <div class="list-container">
          <div class="list-header">
            <div class="header-title">设备列表</div>
            <!-- 设备搜索条件 -->
            <el-form :inline="true" :model="deviceSearchForm" class="search-form">
              <el-form-item label="设备编号">
                <el-input v-model="deviceSearchForm.deviceCode" placeholder="设备编号" size="small" style="width: 120px;"/>
              </el-form-item>
              <el-form-item label="设备名称">
                <el-input v-model="deviceSearchForm.deviceName" placeholder="设备名称" size="small" style="width: 120px;"/>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="handleDeviceSearch" size="small">搜索</el-button>
                <el-button @click="resetDeviceSearch" size="small">重置</el-button>
              </el-form-item>
            </el-form>
          </div>
          <div class="list-content">
            <div
              v-for="item in deviceList"
              :key="item.id"
              class="list-item"
              :class="{ 'list-item-selected': selectedDevice && selectedDevice.id === item.id }"
              @click="handleDeviceClick(item)"
            >
              {{ item.deviceName }}
              <span v-if="item.postName">（{{ item.postName }}）</span>
            </div>
            <div v-if="deviceList.length === 0" class="empty-tip">暂无设备数据</div>
          </div>
          <!-- 分页组件 - 调整padding -->
          <!-- <div class="pagination-container">
            <el-pagination
              background
              :current-page="devicePage.pageNo"
              :page-sizes="[10, 20, 50, 100]"
              :page-size="devicePage.pageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="devicePage.total"
              @size-change="handleDeviceSizeChange"
              @current-change="handleDeviceCurrentChange"
            />
          </div> -->
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import * as DeviceApi from '@/api/lamp/device/index.js';
import {listData} from "@/api/system/dict/data";
import DeviceForm from './DeviceForm.vue';
import request from '@/utils/request'
import {listDept} from "@/api/system/dept";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "Device",
  components: {
    DeviceForm,
    Treeselect
  },
  data() {
    return {
      // 列表数据
      deptList: [],//产线列表
      simpleList: [],//工位原始列表
      filteredPostList: [],//工位过滤后列表
      deviceList: [],//设备列表
      deviceTypeOptions: [],//设备类型列表
      // 选中状态
      selectedDeviceType: null, // 选中的设备类型
      selectedPost: null, // 选中的工位
      selectedDevice: null, // 选中的设备

      // 搜索条件
      postSearchForm: {
        name: '',
        deptId: null // 添加产线ID字段
      },
      deviceSearchForm: {
        deviceCode: '',
        deviceName: ''
      },

      // 分页信息
      devicePage: {
        pageNo: 1,
        pageSize: 10,
        total: 0
      },

      // 查询参数
      queryParams: {
        pageNo: 1,
        pageSize: 10,
        deviceType: null,
        deviceCode: null,
        deviceName: null,
        sortNum: null,
        status: null,
        createTime: [],
      },

      // 加载状态
      loading: true,
    };
  },
  created() {
    this.getOptions();
  },
  methods: {
    // 获取基础数据
    getOptions() {
      // 获取设备类型
      listData({pageNo: 1, pageSize: 100, dictType: 'device_type'}).then(res => {
        this.deviceTypeOptions = res.data.list;
      });


      listDept(this.queryParams).then(response => {
        this.deptList = this.addLevelToNodes(this.handleTree(response.data, "id"), 1);
        this.loading = false;
      });

      const getPostParams = {
        pageNo: 1,
        pageSize: 100,
      };

      request({
        url: '/system/post/page',
        method: 'get',
        params: getPostParams
      }).then(res => {
        this.simpleList = res.data.list
      })
    },

    // 添加产线选择变化处理方法
    handleDeptChange() {
      this.getOptions(); // 当产线改变时重新查询工位列表
    },

    // 递归函数为节点添加层级标记
    addLevelToNodes(nodes, currentLevel = 1) {
      if (!nodes || !Array.isArray(nodes)) {
        return [];
      }
      return nodes.map(node => {
        const newNode = {
          ...node,
          level: currentLevel
        };
        if (node.children && node.children.length > 0) {
          newNode.children = this.addLevelToNodes(node.children, currentLevel + 1);
        }
        return newNode;
      });
    },
    normalizer(node) {
      // 构建基础对象，确保包含 id, label, children 属性
      const normalizedNode = {
        id: node.id,
        label: node.name,
        children: node.children, // 必须包含 children
      };

      // 关键：如果不是第三级节点，则禁用
      if (node.deptType !== 3) {
        normalizedNode.isDisabled = true; // 修改为 isDisabled
      } else {
      }
      return normalizedNode;
    },
    // 获取设备列表（带查询条件）
    getDeviceList() {
      const params = {
        pageNo: this.devicePage.pageNo,
        pageSize: this.devicePage.pageSize,
        deviceType: this.selectedDeviceType,
        deviceCode: this.deviceSearchForm.deviceCode,
        deviceName: this.deviceSearchForm.deviceName
      };

      this.loading = true;
      request({
        url: '/lamp/device/page',
        method: 'get',
        params: params
      }).then(res => {
        this.deviceList = res.data.list;
        this.devicePage.total = res.data.total;
        // 设备列表改变时，清除选中状态
        this.selectedDevice = null;
        this.loading = false;
      }).catch(() => {
        this.loading = false;
      });
    },

    // 处理设备类型点击
    handleDeviceTypeClick(item) {
      this.selectedDeviceType = item.value;
      this.devicePage.pageNo = 1; // 重置为第一页
      console.log('选中的设备类型:', item);
      this.getDeviceList(); // 根据设备类型查询设备列表
    },

    // 处理工位点击
    handlePostClick(item) {
      this.selectedPost = item;
      console.log('选中的工位:', item);
    },

    // 处理设备点击
    handleDeviceClick(item) {
      this.selectedDevice = item;
      console.log('选中的设备:', item);
    },

    // 工位搜索
    handlePostSearch() {
      const getPostParams = {
        pageNo: 1,
        pageSize: 100,
        deptId: this.postSearchForm.deptId,
        name: this.postSearchForm.name
      };

      request({
        url: '/system/post/page',
        method: 'get',
        params: getPostParams
      }).then(res => {
        this.simpleList = res.data.list
      })
    },

    // 重置工位搜索
    resetPostSearch() {
      this.postSearchForm = {
        name: '',
        deptId: null
      };
      this.handlePostSearch(); // 重置后重新查询
    },

    // 设备搜索
    handleDeviceSearch() {
      this.devicePage.pageNo = 1; // 重置为第一页
      this.getDeviceList();
    },

    // 重置设备搜索
    resetDeviceSearch() {
      this.deviceSearchForm = {
        deviceCode: '',
        deviceName: ''
      };
      this.devicePage.pageNo = 1;
      this.getDeviceList();
    },

    // 设备分页 - 每页条数变化
    handleDeviceSizeChange(size) {
      this.devicePage.pageSize = size;
      this.getDeviceList();
    },

    // 设备分页 - 当前页变化
    handleDeviceCurrentChange(current) {
      this.devicePage.pageNo = current;
      this.getDeviceList();
    },

    // 确认绑定按钮点击 - 调用接口
    handleSave() {
      if (this.selectedPost && this.selectedDevice) {
        const data = {
          deviceId: this.selectedDevice.id,
          postId: this.selectedPost.id
        };

        this.$confirm('确定要绑定该设备和工位吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          request({
            url: '/lamp/device/bind',
            method: 'post',
            data: data
          }).then(res => {
            if (res.code === 0) {
              this.$message.success('绑定成功');
              // 绑定成功后清除选中状态
              this.selectedPost = null;
              this.selectedDevice = null;
              this.getOptions();
              // 绑定成功后重新查询设备列表，确保显示最新的绑定状态
              this.getDeviceList();
            } else {
              this.$message.error(res.msg || '绑定失败');
            }
          }).catch(err => {
            this.$message.error('绑定失败，请重试');
          });
        }).catch(() => {
          this.$message.info('已取消绑定');
        });
      }
    },
  },
};
</script>

<style scoped>
/* 顶部操作栏 */
.top-actions {
  padding: 10px 0;
}

/* 列表容器样式 - 提升视觉效果 */
.list-container {
  height: 100%;
  display: flex;
  flex-direction: column;
  border: 1px solid #e8e8e8;
  border-radius: 6px;
  overflow: hidden;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
  transition: box-shadow 0.3s ease;
}

.list-container:hover {
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

/* 列表头部 - 统一高度和样式 */
.list-header {
  padding: 10px 15px;
  background-color: #fafafa;
  border-bottom: 1px solid #e8e8e8;
  font-weight: 500;
  font-size: 14px;
  height: 100px; /* 统一固定高度 */
  display: flex;
  flex-direction: column;
  justify-content: center;
}

/* 标题样式 */
.header-title {
  color: #262626;
  margin-bottom: 8px;
}

/* 搜索表单样式 - 靠右对齐 */
.search-form {
  margin-top: 5px;
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: flex-start;
}

.search-form .el-form-item:last-child {
  margin-left: auto;
}

/* 列表内容区域 - 确保超出部分Y轴滚动 */
.list-content {
  flex: 1;
  overflow-y: auto;
  padding: 10px;
  min-height: 0; /* 修复flex子元素高度计算问题 */
  background-color: #fff;
}

/* 美化滚动条 */
.list-content::-webkit-scrollbar {
  width: 6px;
  height: 6px;
}

.list-content::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.list-content::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.list-content::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

/* 列表项样式 - 提升视觉效果 */
.list-item {
  padding: 10px 12px;
  margin-bottom: 6px;
  background-color: #fff;
  border: 1px solid #e8e8e8;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
}

/* 列表项悬停样式 */
.list-item:hover {
  background-color: #f5f7fa;
  border-color: #409eff;
  transform: translateY(-1px);
  box-shadow: 0 2px 4px rgba(64, 158, 255, 0.1);
}

/* 列表项选中样式 */
.list-item-selected {
  background-color: #e6f7ff !important;
  border-color: #1890ff !important;
  color: #1890ff;
  font-weight: 500;
  box-shadow: 0 2px 8px rgba(24, 144, 255, 0.2);
}

/* 空数据提示样式 */
.empty-tip {
  text-align: center;
  color: #999;
  padding: 40px 20px;
  font-size: 14px;
}

/* 分页容器样式 */
.pagination-container {
  border-top: 1px solid #e8e8e8;
  background-color: #fafafa;
  height: 40px;
}
</style>
